package alert

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"monitor.ilin.cc/config"
)

type DingTalkNotifier struct {
	webhook string
	client  *http.Client
}

type dingTalkMessage struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content string `json:"content"`
	} `json:"text"`
}

func NewDingTalkNotifier(cfg config.AlertChannel) *DingTalkNotifier {
	return &DingTalkNotifier{
		webhook: cfg.Webhook,
		client: &http.Client{
			Timeout: 5 * time.Second,
		},
	}
}

func (n *DingTalkNotifier) Send(message string) error {
	msg := dingTalkMessage{
		MsgType: "text",
	}
	msg.Text.Content = message

	jsonData, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("marshal message failed: %v", err)
	}

	resp, err := n.client.Post(n.webhook, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("send request failed: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	return nil
}
